<template>
	<view class="page">
    <u-navbar :fixed="false" title="库存查询" :autoBack="true" bgColor="transparent"></u-navbar>
    <view class="content">
      <view class="search" v-if="!type">
        <view class="search-type" @click="pickerType = 'type'">{{ form.typeName }}
          <u-icon name="arrow-down" size="24rpx"></u-icon>
        </view>
        <u-search
          placeholder="请输入"
          v-model="searchValue"
          @search="search"
          :showAction="false"
        ></u-search>
      </view>
      <view v-if="list.length">
        <view class="box">
          <u-icon name="arrow-left" :color="listIndex != 0 ?'#000':'#c8c9cc'" size="32rpx" @click="changeIndex(-1)"></u-icon>
          <view class="u-flex-1 u-text-center">{{ listIndex + 1 }} / {{ list.length }}</view>
          <u-icon name="arrow-right" :color="listIndex != list.length -1 ?'#000':'#c8c9cc'" size="32rpx" @click="changeIndex(1)"></u-icon>
        </view>
        <view class="list">
          <view class="list-item">
            <view class="code">
              <view class="u-line-1">品牌：{{ list[listIndex].Brand }} </view>
              <view class="status"><u-icon name="photo" color="#2979ff" size="28" @click="imageBig(list[listIndex].FmaterialNumber)"></u-icon></view>
            </view>
            <view class="info">
              <view class="info-item">
                <image src="../../static/icon/编号.png" mode="widthFix" />
                <text>
                  编&emsp;&emsp;码：{{ list[listIndex].FmaterialNumber }}
                </text>
              </view>
              <view class="info-item" @click.stop="call(item.phone)">
                <image src="../../static/icon/名称.png" mode="widthFix" />
                <text>
                  名&emsp;&emsp;称：{{ list[listIndex].FmaterialName }}
                </text>
              </view>
              <view class="info-item">
                <image src="../../static/icon/规格.png" mode="widthFix" />
                <text>
                  规&emsp;&emsp;格：{{ list[listIndex].ModelName }}
                </text>
              </view>
            </view>
            <view class="time">
              <view>
                <text class="lable">总可用量</text>
                <text>{{ list[listIndex].UseQty }}</text>
              </view>
              <view>
                <text class="lable">总库存量</text>
                <text>{{ list[listIndex].ExistQty }}</text>
              </view>
            </view>
          </view>
        </view>
        <view v-if="list.length" style="width: 280rpx;" class="saveBase u-m-t-30 u-m-b-30" @click="uploadImg">上传物料图片</view>
        <view class="list-title-text u-m-b-20"><view class="text">商品属性</view><view class="line" /></view>
        <view class="table-box">
          <uni-table align="left" border :stripe="false" emptyText="暂无更多数据" >
            <!-- 表头行 -->
            <uni-tr>
              <uni-th v-for="(item, index) in columns" :width="item.width" :key="index">{{ item.title }}</uni-th>
            </uni-tr>
            <!-- 表格数据行 -->
            <uni-tr v-for="item in list[listIndex].Links" :key="item.StockId">
              <uni-td v-for="(zitem, zindex) in columns" :width="zitem.width" :key="zindex">
                <template v-if="zitem.slot">
                  <template v-if="zitem.key=='actions'">
                    <text class="u-color-primary" @click="toPosition(item)">查看</text>
                  </template>
                </template>
                <template v-else>
                  {{ item[zitem.key] }}
                </template>
              </uni-td>
            </uni-tr>
          </uni-table>
        </view>
      </view>
      <view class="box" style="display: block;" v-else>
        <u-empty></u-empty>
      </view>
    </view>
    <u-picker ref="uPicker" :show="pickerType!=''" :columns="[pickerInfo[pickerType]]" keyName="name" @confirm="pickerConfirm" @cancel="pickerType = ''"></u-picker>
		<u-overlay :show="overlayShow" @click="overlayShow = false">
			<image class="overlayImage" :src="overlayImg" mode="widthFix"></image>
			<view class="saveBase" @click="saveBase">保存图片</view>
		</u-overlay>
  </view>
</template>

<script>
import { getExecuteService, getExecuteServiceImg, getBaseImg, getExecuteSaveImage, UploadFile } from '@/api/index'

export default {
  data() {
    return {
      searchValue: '000024',
      pickerType: '',
      pickerInfo: {
         type: [
          {
            id: 'Materidal',
            name: '物料编码'
          },
          {
            id: 'MaterialName',
            name: '物料名称',
          },
          {
            id: 'ModelName',
            name: '规格型号'
          },
        ],
      },
      form: {
        typeName: '物料编码',
        type: 'Materidal',
      },
      list: [],
      listIndex: 0,
      columns: [
        {
          title: '操作',
          key: 'actions',
          width: '120rpx',
          slot: true,
        },
        {
          title: '仓库名称',
          width: '300rpx',
          key: 'StockName',
        },
        {
          title: '现存量',
          width: '140rpx',
          key: 'ExistQty',
        },
        {
          title: '可用量',
          width: '140rpx',
          key: 'UseQty',
        },
      ],
      orgId: '',
      Materidal: '',
      type: '',
      overlayShow: false,
      overlayImg: '',
    }
  },
  onLoad(options) {
    this.orgId = options.orgId
    this.searchValue = options.Materidal
    this.type = options.type
    if(this.type) {
      this.getForm()
    }
  },
  methods: {
    uploadImg() {
      const that = this
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          wx.getFileSystemManager().readFile({
            filePath: res.tempFiles[0].tempFilePath, //要读取的文件的路径 (本地路径)
            encoding: "base64", //指定读取文件的字符编码，如果不传 encoding，则以 ArrayBuffer 格式读取文件的二进制内容
            async success(res) {
              const parameters = { "data": { "FileName": that.list[that.listIndex].FmaterialNumber+'.png', "IsLast": true, "SendByte": res.data } }
              uni.showLoading({ mask: true });
              const resUpload = await UploadFile(parameters)
              uni.hideLoading()
              if(resUpload.Result && resUpload.Result.FileId) {
                await getExecuteSaveImage({json: JSON.stringify({ MaterialNumber: that.list[that.listIndex].FmaterialNumber, Fileid: resUpload.Result.FileId })})
                uni.hideLoading()
                uni.showToast({
                  title: '上传成功',
                  icon: 'none',
                })
              } else {
                uni.showToast({
                  title: '图片上传服务器失败',
                  icon: 'none',
                })
              }
            }
          })
        }
      })
    },
    getForm() {
      if(this.searchValue.trim()!== '') {
        uni.showLoading({ mask: true });
        // 物料编码：Materidal。规格型号：ModelName。物料名称：MaterialName
        const parameters = {
          Materidal: '',
          ModelName: '',
          MaterialName: '',
          orgNumber: this.orgId
        }
        if(this.form.type == 'Materidal') {
          parameters.Materidal = this.searchValue
        } else if(this.form.type == 'MaterialName') {
          parameters.MaterialName = this.searchValue
        } else {
          parameters.ModelName = this.searchValue
        }
        getExecuteService({json: JSON.stringify(parameters)}).then(res => {
          uni.hideLoading()
          if(res.Material.length && res.Material[0].msg !=='未查出数据') {
						res.Material.forEach(v => {
              if(v.Links.length == 1 && v.Links[0].StockId == '') {
                v.Links = []
              }
							v.UseQty = v.Links.reduce((sum, item) => {
								return sum + item.UseQty*1
							}, 0)
							v.ExistQty = v.Links.reduce((sum, item) => {
								return sum + item.ExistQty*1
							}, 0)
						})
            this.list = res.Material
            this.listIndex = 0
          } else {
            uni.showToast({
              icon: 'none',
              title: '无数据',
            })
          }
        })
      } else {
        uni.showToast({
          title: '请输入内容',
          icon: 'none'
        });
      }
    },
    toPosition(item) {
      const parameters = {
        materialNumber: this.list[this.listIndex].FmaterialNumber,
        stockOrgNumber: this.orgId,
        stockNumber: item.StockId
      }
      this.jumpTo('/pages/queryPosition/queryPosition', parameters)
    },
    search() {
      this.getForm()
    },
    pickerConfirm(e) {
      if(e.value[0].id) {
        this.form[this.pickerType] = e.value[0].id
        this.form[this.pickerType+'Name'] = e.value[0].name
      } else {
        this.form[this.pickerType] = ''
        this.form[this.pickerType+'Name'] = ''
      }
      this.pickerType = ''
      this.searchValue = ''
    },
    changeIndex(num) {
      if(num == -1) {
        if(this.listIndex > 0) {
          this.listIndex = this.listIndex + num
        }
      } else {
        if(this.listIndex < this.list.length - 1) {
          this.listIndex = this.listIndex + num
        }
      }
    },
    imageBig(idCode) {
      uni.showLoading({ mask: true });
      getExecuteServiceImg({ "parameters": [ {"MaterialNumber": idCode, "token": uni.getStorageSync('token')} ]}).then(res => {
        function getQueryParam(url, param) {
          // 构造正则表达式，匹配 ? 或 & 后面跟随的参数名称和其值
          const regex = new RegExp('[?&]' + param + '=([^&#]*)', 'i');
          const result = regex.exec(url);
          return result ? decodeURIComponent(result[1]) : null;
        }
        getBaseImg({ "parameters": [ {"FileId": getQueryParam(res.Url, 'fileId'), "StartIndex": 0 } ]}).then(bres => {
          if(bres.Result.FilePart) {
            uni.hideLoading();
            this.overlayImg = 'data:image/png;base64,' + bres.Result.FilePart
            this.overlayShow = true
          } else {
            uni.showToast({
              title: "暂无图片",
              icon: 'none'
            });
          }
        })
      })
    },
    saveBase64ToPhotoAlbum(base64Data) {
      // 1. 去除Base64头部信息（如："data:image/png;base64,"）
      const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
      // 2. 转换为ArrayBuffer
      const arrayBuffer = uni.base64ToArrayBuffer(base64);
      // 3. 生成临时文件路径
      const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;
      // 4. 写入文件
      const fs = uni.getFileSystemManager();
      return new Promise((resolve, reject) => {
        fs.writeFile({
        filePath,
        data: arrayBuffer,
        encoding: 'binary',
        success: () => {
          // 5. 保存到相册
          uni.saveImageToPhotosAlbum({
            filePath,
            success: () => resolve('保存成功'),
            fail: (err) => reject('保存失败，请检查权限：' + err.errMsg),
          });
        },
        fail: (err) => reject('文件写入失败：' + err.errMsg),
        });
      });
    },
    async saveBase() {
      try {
        uni.showLoading({ mask: true });
        const base64 = this.overlayImg;
        await this.saveBase64ToPhotoAlbum(base64);
        uni.hideLoading()
        uni.showToast({ title: '保存成功', icon: 'success' });
        console.error("保存图片成功");
      } catch (error) {
        console.error("保存图片失败 error：", error);
        uni.showToast({ title: error, icon: 'none' });
        // 处理权限被拒绝的情况
        if (error.includes('authorize')) {
        uni.openSetting({}); // 引导用户打开权限设置
        }
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.page{
	width: 750rpx;
	min-height: 100vh;
  padding-bottom: 188rpx;
  .content {
    width: 100%;
    padding: 0 30rpx;
  }
  .search {
    margin-top: 20rpx;
    padding: 16rpx 20rpx;
    background: #FFF;
    border-radius: 20rpx;
    box-shadow: 3rpx 3rpx 4rpx rgba(0, 0, 0, 0.16);
    display: flex;
    align-items: center;
    .search-type {
      width: 180rpx;
      margin-right: 10rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      gap: 6rpx;
    }
  }
  .box {
    margin-top: 20rpx;
    padding: 16rpx 20rpx;
    background: #FFF;
    border-radius: 20rpx;
    box-shadow: 3rpx 3rpx 4rpx rgba(0, 0, 0, 0.16);
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .list {
    width: 100%;
    padding: 40rpx 0 30rpx;
    .list-item {
      overflow: hidden;
      margin-bottom: 24rpx;
      padding: 24rpx 0 0;
      width: 100%;
      border-radius: 20rpx;
      background: #FFF;
      box-shadow: 0 4rpx 20rpx -3rpx rgba(0, 0, 0, 0.31);
      position: relative;
      .code {
        padding: 0 36rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #999;
        font-family: "PingFang SC";
        font-size: 26rpx;
        margin-bottom: 24rpx;
        .status {
          color: #FF8819;
        }
      }
      .info {
        padding: 0 36rpx;
        margin-bottom: 30rpx;
        .info-item {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          color: #333;
          font-size: 28rpx;
          margin-bottom: 16rpx;
          image {
            width: 28rpx;
            height: auto;
            margin-right: 20rpx;
          }
        }
      }
      .time {
        width: 100%;
        padding: 16rpx 36rpx;
        background: #F1F5FF;
        view {
          margin-bottom: 10rpx;
          color: #FF881A;
          font-family: "PingFang SC";
          font-size: 26rpx;
          .lable {
            margin-right: 32rpx;
            color: #333;
          }
        }
      }
      .footer {
        padding: 0 36rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .type {
          color: #FF881A;
          font-size: 26rpx;
          .lable {
            color: #333;
          }
        }
        .oper {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          .btn {
            width: 164rpx;
            height: 58rpx;
            border-radius: 52rpx;
            border: 2rpx solid #4D7AF8;
            color: #4D7AF8;
            font-size: 32rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .btn:first-child {
            margin-right: 30rpx;
          }
        }
      }
    }
  }
  .table-box {
    box-shadow: 3rpx 3rpx 4rpx rgba(0, 0, 0, 0.16);
  }
  .sub-btn {
    width: 630rpx;
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    border-radius: 50rpx;
    background: #2979ff;
    color: #FFF;
    font-family: "PingFang SC";
    font-size: 36rpx;
    position: fixed;
    bottom: 42rpx;
    left: 60rpx;
  }
}
.overlayImage {
  width: 80%;
  height: auto;
  margin: 300rpx auto 50rpx;
}
.saveBase {
  width: 200rpx;
  height: 60rpx;
  line-height: 60rpx;
  color: #fff;
  background-color: #2677f0;
  text-align: center;
  border-radius: 50rpx;
  margin: 0 auto;
}
</style>
